package net.rlair.esAnalyzeWord.util;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @version 1.0.0.0
 * @author rlair
 */
public final class JsonMapper {

    /**
     * filed.
     */
    private static ObjectMapper aNONEEMPTYMAPPER;

    /**
     * filed.
     */
    private static ObjectMapper aNOMALMAPPER;

    /**
     * filed.
     */
    private ObjectMapper mapper;

    /**
     * 禁用默认构造函数.
     */
    private JsonMapper() {
    }

    /**
     * 构造函数.
     *
     * @param mapper 需要使用的mapper
     */
    private JsonMapper(final ObjectMapper mapper) {
        this.mapper = mapper;
    }

    /**
     * 获取不输出空值的mapper.
     *
     * @return JsonMapper.
     */
    public static JsonMapper buildNoneEmptyMapper() {
        if (aNOMALMAPPER == null) {
            final ObjectMapper mapper = new ObjectMapper();
            aNOMALMAPPER = mapper;
        }
        return new JsonMapper(aNOMALMAPPER);
    }

    /**
     * 获取普通的mapper.
     *
     * @return JsonMapper.
     */
    public static JsonMapper buildNormalMapper() {
        if (aNONEEMPTYMAPPER == null) {
            final ObjectMapper mapper = new ObjectMapper();
            mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
            mapper.configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, false);
            aNONEEMPTYMAPPER = mapper;
        }
        return new JsonMapper(aNONEEMPTYMAPPER);
    }

    /**
     * 将对象转换为json字符串.
     *
     * @param obj 对象
     * @return json字符串
     */
    public String toJson(final Object obj) {
        try {
            return mapper.writeValueAsString(obj);
        } catch (final JsonProcessingException ex) {
            Logger.getLogger(JsonMapper.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

    /**
     * 将json字符串转换为对象.
     *
     * @param json json字符串
     * @param valueType 类型
     * @param <T> 类型
     * @return 返回对象
     */
    public <T extends Object> T formJson(final String json, final Class<T> valueType) {
        try {
            return mapper.readValue(json, valueType);
        } catch (final Exception ex) {
            Logger.getLogger(JsonMapper.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

    /**
     * 将json字符串转换为对象.
     *
     * @param json json字符串
     * @param valueType 类型
     * @param <T> 类型
     * @return 返回对象
     */
    public <T extends Object> T formJson(final String json, final TypeReference valueType) {
        try {
            return mapper.readValue(json, valueType);
        } catch (final Exception ex) {
            Logger.getLogger(JsonMapper.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

}
